//
//  UIButton+APMActivityIndicator.m
//  FXManager
//
//  Created by lcj on 2020/12/8.
//  Copyright © 2020 华旅电子. All rights reserved.
//

#import "UIButton+APMActivityIndicator.h"
#import <objc/runtime.h>

static char APMButtonActivityIndicatorKey;
@interface UIButton (_APMActivityIndicator)
@property (readwrite, nonatomic, strong, setter = apm_setIndicatorView:)UIActivityIndicatorView * apm_indicatorView;
@end

@implementation UIButton (_APMActivityIndicator)
- (UIActivityIndicatorView *)_apm_indicatorView {
    UIActivityIndicatorViewStyle style = UIActivityIndicatorViewStyleWhite;
    if (@available(iOS 13.0, *)) {
        style = UIActivityIndicatorViewStyleMedium;
    }
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
    indicatorView.hidesWhenStopped = YES;
    indicatorView.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    [self addSubview:indicatorView];
    return indicatorView;
}

- (UIActivityIndicatorView *)apm_indicatorView {
    UIActivityIndicatorView *indicatorView = (UIActivityIndicatorView *)objc_getAssociatedObject(self, &APMButtonActivityIndicatorKey);
    if (indicatorView == nil) {
        indicatorView = [self _apm_indicatorView];
        self.apm_indicatorView = indicatorView;
    }
    return indicatorView;
}

- (void)apm_setIndicatorView:(UIActivityIndicatorView *)indicatorView {
    objc_setAssociatedObject(self, &APMButtonActivityIndicatorKey, indicatorView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end


@implementation UIButton (APMActivityIndicator)

- (void)apm_setIndicatorTintColor:(UIColor *)tintColor {
    if ([NSThread isMainThread]) {
        self.apm_indicatorView.color = tintColor;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.apm_indicatorView.color = tintColor;
        });
    }
}

- (void)apm_setIndicatorCenter:(CGPoint)center {
    if ([NSThread isMainThread]) {
        self.apm_indicatorView.center = center;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.apm_indicatorView.center = center;
        });
    }
}

- (void)apm_startAnimating {
    if ([NSThread isMainThread]) {
        [self.apm_indicatorView startAnimating];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.apm_indicatorView startAnimating];
        });
    }
}

- (void)apm_stopAnimating {
    if ([NSThread isMainThread]) {
        [self.apm_indicatorView stopAnimating];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.apm_indicatorView stopAnimating];
        });
    }
}
@end
